import { useState, useEffect } from 'react'
import { useChatRoom } from './useChatRoom';

// 定义Props泛型接口
interface ChatRoomProps<T> {
  roomId: string;
}
function ChatRoom<T>({roomId}:ChatRoomProps<T>) {

  const [serverUrl, setServerUrl] = useState('https://loaclhost:3333')

  // useEffect 部分抽离成 hook 函数 这样 链接chat 就可以在多个组件复用

  useChatRoom(serverUrl, roomId)

  // useEffect(()=>{
  //   const connetction = createConnection(serverUrl, roomId)
  //   connetction.connect()
  //   return () => {
  //     connetction.disconnect()
  //   }
  // }, [roomId, serverUrl])

  return (
    <>
      <label>
        Server URL:{' '}
        <input
          value={serverUrl}
          onChange={e => setServerUrl(e.target.value)}
        />
      </label>
      <h1>Welcome to the {roomId} room!</h1>
    </>
  );
}


export default function ChatPage(){
  const [roomId, setRoomId] = useState('general');
  const [show, setShow] = useState(false);
  return (
    <>
      <label>
        Choose the chat room:{' '}
        <select
          value={roomId}
          onChange={e => setRoomId(e.target.value)}
        >
          <option value="general">general</option>
          <option value="travel">travel</option>
          <option value="music">music</option>
        </select>
      </label>
      <button onClick={() => setShow(!show)}>
        {show ? 'Close chat' : 'Open chat'}
      </button>
      {show && <hr />}
      {show && <ChatRoom roomId={roomId} />}
    </>
  );
}